package com.rainyun.rd.controller;

import com.rainyun.rc.command.ConvertException;
import com.rainyun.rc.command.annotation.BeanCmd;
import com.rainyun.rc.config.NodeConfig;
import com.rainyun.rc.ioc.Beanzy;
import com.rainyun.rc.orm.RainDB;
import com.rainyun.rcmc.bukkit.BukCmdPath;
import com.rainyun.rcmc.bukkit.annotation.Buk;
import com.rainyun.rd.biz.BizCommon;
import com.rainyun.rd.common.BeanRd;
import com.rainyun.rd.common.RdCmdAttr;
import com.rainyun.rd.common.RdPerm;
import com.rainyun.rd.config.RdLang;
import com.rainyun.rd.entity.PlayerInfo;
import com.rainyun.rd.main.RainDemo;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


/**rd指令节点主类*/
@Buk
@BeanCmd("raindemo")
@RdCmdAttr(
		perm = RdPerm.RD_Base,
		help = "&8 v{version} by Akr_on",
		alias = {"rd"} //指令别名
)
public class CmdRD extends BukCmdPath{

	@Beanzy
	static RainDemo plugin;
	@BeanRd(BeanRd.BeansRd.NodeConf)
	static NodeConfig<?> ncf;
	@Beanzy
	static BizCommon bizCommon;

	@BeanRd(BeanRd.BeansRd.DBMan)
	static RainDB db;

	/**初始化*/
	@Override
	public void init() {

		//补全器
		this.addTabExec("p_info",(sd, pathname, args) -> {
			if("player".equals(pathname))
			try {
				return db.newSql(PlayerInfo.class).select("@name").getResultList();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return new ArrayList<>();
		});

	}

	@Override
	public void sendWithPrefix(CommandSender sd, String msg) {
		bizCommon.sendWithPrefix(sd,msg);
	}
	@Override
	public void sendMsg(CommandSender sd, String msg) {
		bizCommon.sendMsg(sd,msg);
	}

	@Override
	public Plugin getPlugin() {
		return plugin;
	}

	@Override
	public <T> T getAttr(Object name) {
		T attr = null;
		//前后缀设置
		if(name.equals("help_prefix"))
			attr=ncf.get(RdLang.cmd_help_prefix);
		else if(name.equals("help_suffix"))
			attr=ncf.get(RdLang.cmd_help_suffix);
		else attr=super.getAttr(name);

		//版本占位符替换
		if(attr!=null&&"raindemo".equals(this.getName())&&"help".equals(name))
			attr= (T) attr.toString().replace("{version}",plugin.getDescription().getVersion());
		return attr;
	}

	/**参数自定义转换(默认已自动转换数字/玩家/离线玩家)*/
	@Override
	public <T> T convert(Class<T> clazz, String str, CommandSender sd) throws ConvertException {
		//强行覆盖
//		if(clazz.equals(Player.class)) {
//			sd.sendMessage(str+"不是玩家");
//			return (T)p;
//		}
		//扩展
		try {
			T result = super.convert(clazz, str, sd);
			if(result==null) {
//				if(clazz.equals(Dog.class)) {
//					sd.sendMessage(str+"不是狗狗");
//					if(true)throw new ConvertException(Dog.class);
//					result = (T) new Dog();
//				}
			}
			return result;
		}catch (ConvertException e){

			throw e;
		}
	}

	@Override
	public void handleExecError(CommandSender sd, Throwable e) {
		e.printStackTrace();
		bizCommon.sendWithPrefix(sd,ncf.get(RdLang.error));
	}

	//下面这里也可以使用cmdline,但为了模块化建议在biz内使用

}









